﻿using System.Xml.Serialization;

namespace Tools.Android
{
    public static class ConfigHelper
    {
        private static string _configPath = Path.Combine(
            Application.StartupPath,
            "MySQLConnectionManager",
            "connections.xml");

        static ConfigHelper()
        {
            // 确保配置文件目录存在
            string directory = Path.GetDirectoryName(_configPath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
        }

        // 保存连接信息列表
        public static void SaveConnections(List<ConnectionInfo> connections)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<ConnectionInfo>));
                using (FileStream stream = new FileStream(_configPath, FileMode.Create))
                {
                    serializer.Serialize(stream, connections);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("保存连接信息失败: " + ex.Message);
            }
        }

        // 加载连接信息列表
        public static List<ConnectionInfo> LoadConnections()
        {
            try
            {
                if (!File.Exists(_configPath))
                {
                    return new List<ConnectionInfo>();
                }

                XmlSerializer serializer = new XmlSerializer(typeof(List<ConnectionInfo>));
                using (FileStream stream = new FileStream(_configPath, FileMode.Open))
                {
                    return (List<ConnectionInfo>)serializer.Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("加载连接信息失败: " + ex.Message);
            }
        }

        // 检查连接名称是否已存在
        public static bool ConnectionNameExists(string connectionName)
        {
            List<ConnectionInfo> connections = LoadConnections();
            return connections.Exists(c => c.ConnectionName.Equals(connectionName, StringComparison.OrdinalIgnoreCase));
        }
    }
}
